package com.huaxin.hxcloud.fragment;

import android.app.Dialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.CheckTaskDetailDTO;
import com.huaxin.common.Entity.HxPunchCardReportBean;
import com.huaxin.common.Entity.HxPunchCardSummaryBean;
import com.huaxin.common.Entity.HxPunchCardViewBean;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.HxUtils;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxin.hxcloud.R;
import com.jeek.calendar.widget.calendar.CalendarUtils;
import com.jeek.calendar.widget.calendar.OnCalendarClickListener;
import com.jeek.calendar.widget.calendar.WeekBarView;
import com.jeek.calendar.widget.calendar.month.MonthCalendarView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author songxf
 * @date 2017/11/23
 * @Desc 考勤---->统计
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxPunchStatisticsFragment extends BaseFragment {


    @BindView(R.id.toolbar)
    Toolbar           mToolbar;
    @BindView(R.id.head_img)
    AvatarImageView   mHeadImg;
    @BindView(R.id.user_name_tv)
    TextView          mUserNameTv;
    @BindView(R.id.month_tv)
    TextView          mMonthTv;
    @BindView(R.id.punch_gate_count_tv)
    TextView          mPunchGateCountTv;
    @BindView(R.id.punch_late_count_tv)
    TextView          mPunchLateCountTv;
    @BindView(R.id.punch_leave_count_tv)
    TextView          mPunchLeaveCountTv;
    @BindView(R.id.punch_outwork_count_tv)
    TextView          mPunchOutworkCountTv;
    @BindView(R.id.weekindcator_lv)
    WeekBarView       mWeekindcatorLv;
    @BindView(R.id.mcvCalendar)
    MonthCalendarView mMcvCalendar;
    @BindView(R.id.punch_count_tv)
    TextView          mPunchCountTv;
    @BindView(R.id.punch_recyclerview)
    RecyclerView      mPunchRecyclerview;
    @BindView(R.id.content)
    FrameLayout       mContent;

    private boolean isShowDialog = false;
    private Dialog                   mDialog;
    private HxPunchStatisticsAdapter mPunchStatisticsAdapter;
    private List<HxPunchCardReportBean.DataBean> mSignBeanList = new ArrayList<>();
    private int mCurrentSelectYear;
    private int mCurrentSelectMonth;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_punch_statistics;
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(mToolbar);
    }

    @Override
    protected void initData() {
        HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
        instance.setHeadImage(getContext(), Global.user.getImgUrl(), Global.user.getNickName(), mHeadImg);
        mUserNameTv.setText(Global.user.getNickName());
        mMonthTv.setText((HxUtils.getMonth() + "月考勤总汇"));
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mDialog = DialogUtil.getWaitDialog(getContext(), "加载中...");
        initRecyclerView();
        initCalendar();
    }

    private void initCalendar() {
        mCurrentSelectYear = HxUtils.getYear();
        mCurrentSelectMonth = HxUtils.getMonth() - 1;
        mMcvCalendar.setOnCalendarClickListener(new OnCalendarClickListener() {
            @Override
            public void onClickDate(int year, int month, int day) {
                String today = year + "-" + (month + 1) + "-" + day;
                requestTodayData(today, !isShowDialog);
            }

            @Override
            public void onPageChange(int year, int month, int day) {
                mCurrentSelectYear = year;
                mCurrentSelectMonth = month;
            }
        });

    }


    private void initRecyclerView() {
        mPunchStatisticsAdapter = new HxPunchStatisticsAdapter(getContext());
        mPunchRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        mPunchRecyclerview.setHasFixedSize(true);
        mPunchRecyclerview.setAdapter(mPunchStatisticsAdapter);
    }

    @Override
    protected void requestData() {
        requestStaticstis();
        requestTodayData(HxUtils.getYearMonthDay(), isShowDialog);
    }

    private int mPunchCount;

    private void requestTodayData(final String today, boolean isShowDialog) {
        isShowDialog(isShowDialog);
        mPunchStatisticsAdapter.getData().clear();
        Call<HxPunchCardReportBean> beanCall = HxTransmitRequestHelper.getRequestApi().getReportDay(today);
        autoClose(beanCall);
        beanCall.enqueue(new Callback<HxPunchCardReportBean>() {
            @Override
            public void onResponse(Call<HxPunchCardReportBean> call, Response<HxPunchCardReportBean> response) {
                List<HxPunchCardReportBean.DataBean> dataBeanList = response.body().getData();
                cancleDialog();
                if (response.isSuccessful()) {
                    mSignBeanList.clear();
                    if (dataBeanList != null) {
                        mSignBeanList.addAll(dataBeanList);
                        mPunchCount = dataBeanList.size();
                    } else {
                        mPunchCount = 0;
                    }
                    mPunchStatisticsAdapter.setNewData(mSignBeanList);
                    mPunchCountTv.setText(("今天打卡" + mPunchCount + "次"));

                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<HxPunchCardReportBean> call, Throwable t) {
                cancleDialog();
            }
        });

    }

    /**
     * 是否显示dialog
     *
     * @param isShow
     */
    private void isShowDialog(boolean isShow) {
        if (isShow) {
            mDialog.show();
        }
    }

    /**
     * 隐藏dialog
     */
    private void cancleDialog() {
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
    }

    /**
     * 统计接口
     */
    private void requestStaticstis() {
        updateLoadStatus(LOADING);
        Call<HxPunchCardSummaryBean> call = HxTransmitRequestHelper.getRequestApi().getSummary(HxUtils.getYearMonth());
        autoClose(call);
        call.enqueue(new Callback<HxPunchCardSummaryBean>() {
            @Override
            public void onResponse(Call<HxPunchCardSummaryBean> call, Response<HxPunchCardSummaryBean> response) {
                HxPunchCardSummaryBean.DataBean dataBean = response.body().getData();
                if (response.isSuccessful()) {

                    HxPunchCardSummaryBean.DataBean.ReportBean reportBean = dataBean.getReport();
                    addTaskHintMap(dataBean.getCalendar().getAttendances());
                    setPunchStatisData(reportBean.getWorkday()
                            , reportBean.getLate(), reportBean.getEarly(), reportBean.getOutside());
                    updateLoadStatus(LOAD_SUCCESS);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<HxPunchCardSummaryBean> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);

            }
        });
    }

    /**
     * @param attendancesBeans
     * @desc 显示日历小标记
     * @author songxf
     * created at 2017/12/5 16:00
     */
    public void addTaskHintMap(List<HxPunchCardSummaryBean.DataBean.CalendarBean.AttendancesBean> attendancesBeans) {
        List<Map<String, Integer>> hints = new ArrayList<>();
        HashMap<String, Integer> markData = new HashMap<>();
        int markState;
        if (attendancesBeans != null) {
            for (HxPunchCardSummaryBean.DataBean.CalendarBean.AttendancesBean attendancesBean : attendancesBeans) {
                String date = attendancesBean.getDate();
                if (!attendancesBean.isNormal()) {
                    markState = 1;
                } else {
                    markState = 2;
                }
                markData.put(date, markState);
            }
            hints.add(markData);
            CalendarUtils.getInstance(getContext()).addTaskHintMap(mCurrentSelectYear, mCurrentSelectMonth, hints);
            if (mMcvCalendar.getCurrentMonthView() != null) {
                mMcvCalendar.getCurrentMonthView().invalidate();
            }
        }
    }


    /**
     * @param workday 出勤次数
     * @param late    迟到次数
     * @param early   早退次数
     * @param outside 外勤次数
     */
    private void setPunchStatisData(int workday, int late, int early, int outside) {
        mPunchGateCountTv.setText((workday + "天"));
        mPunchLateCountTv.setText((late + "天"));
        mPunchLeaveCountTv.setText((early + "天"));
        mPunchOutworkCountTv.setText((outside + "天"));
    }


}
